package com.tanhua.admin.listener;

import com.alibaba.fastjson.JSON;
import com.tanhua.admin.mapper.LogMapper;
import com.tanhua.model.domain.Log;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class LogListener {//配置监听器:用于接收server发送的日志
         @Autowired
        private LogMapper logMapper;

    @RabbitListener(//监听器对应注解
            bindings = @QueueBinding(
                    value=@Queue(
                            value = "tanhua.log.queue",//名称任意,声明队列名称
                            durable = "true"  // 是否持久化,是否写入到硬盘中
                    ),
                    exchange = @Exchange(//交换机
                            value = "tanhua.log.exchange",//交换机名称,必须和发送消息的一致
                            type = ExchangeTypes.TOPIC
                    ),
                    key = "log.*"
            )
    )
    public void log(String message){//接收消息
        Map map = JSON.parseObject(message, Map.class);//格式转化
        //遍历集合
        map.forEach((k,v)->{
            System.out.println(k+"--"+v);
        });
        //1、解析MAP获取数据
        Long userId = Long.valueOf(map.get("userId").toString());
        String type = (String) map.get("type");
        String logTime = (String) map.get("logTime");
        //2、构造log对象，保存到数据库中
        Log log = new Log(userId,logTime,type);
        logMapper.insert(log);

    }
}
